﻿var utility = require('system/utility'),
	DataBase = require('./sql-tedious'),
	DataSet = require('dataAccess/dataset'),
	db = null,
	app;

DataSet.setDataRow(DataBase.DataRow);

function log() { utility.log("test1", arguments); }

function Test1(appX) {
	app = appX;
	app.router.addHandler({ name: 'echo', fn: this.echo, scope: this });
	app.router.addHandler({ name: 'request', fn: this.request, scope: this });
	app.router.addHandler({ name: 'hello', fn: this.hello, scope: this });
	app.router.addHandler({ name: 'goodbye', fn: this.goodbye, scope: this });
	app.router.addHandler({ name: 'sqlForm', fn: this.sqlForm, scope: this });
	// would now call other controllers and pass them their basePath...
}

Test1.prototype.echo = function (rqFrame, callback) {
	//callback(rqFrame.);
}

Test1.prototype.request = function (rqFrame, callback) {
	var resp = { success: true, data: {} };
	if (rqFrame._info) {
		resp.data.qs = rqFrame._info.queryString;
		resp.data.post = rqFrame._info.postData;
	} else {
		resp.data.info = "set http server setting debug=true to view request data";
	}
	log("/REQUEST: ", resp);
	callback(resp);
}

Test1.prototype.hello = function (rqFrame, callback) {
	callback("Hello... " + (rqFrame.msg || ""));
}

Test1.prototype.goodbye = function (rqFrame, callback) {
	callback("Goodbye... " + (rqFrame.msg || ""));
}

Test1.prototype.sqlForm = function (rqFrame, callback) {
	var query = rqFrame.sqlQuery;
	try {
		if (query) {
			DataBase.query(query, {}, callback);
		} else {
			callback({ data: { success: false, errors: ['no sqlQuery']} });
		}
	} catch (e) {
		log("*** sqlForm error: ", e);
		callback({ data: { success: false, errors: ["SQL exception: " + e.toString()]} });
	}
};

module.exports = Test1;